package com.zc.rpc.interceptor.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * feign拦截处理传递token
 *
 * @author zcj
 * @version 1.0.0
 * @date 2022/6/14 17:45
 */
public class FeignHeaderTokenInterceptor implements RequestInterceptor {

    private static final String AUTHORIZATION = "Authorization";

    /**
     * auth-security-processor包中token处理到 {@link Authentication credentials}中
     *
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {
        SecurityContext context = SecurityContextHolder.getContext();
        if (context == null) {
            return;
        }
        Authentication authentication = context.getAuthentication();
        if (authentication == null) {
            return;
        }
        // 添加Authorization请求头
        template.header(AUTHORIZATION, (String) authentication.getCredentials());
    }
}
